package cn.myproject.articletype.controller;
import cn.myproject.articletype.domian.Article;
import cn.myproject.articletype.query.ArticleQuery;
import cn.myproject.articletype.service.IArticleservice;
import cn.myproject.excption.myexcption;
import cn.myproject.util.R;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private IArticleservice articleservice;
    /**
     * 新增文章
     */

    @PostMapping("/add")
    public R inert(@RequestBody Article article){
        try {
            articleservice.addArticle(article);
            return R.ok("登录成功");
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            return R.fail("系统错误，联系工作人员");
        }
    }

    /**
     *修改文章
     * */
    @PostMapping("/updata")
    public R updata(@RequestBody Article article){
        try {
            articleservice.updata(article);
            return R.ok("修改成功");
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return R.fail("系统错误，联系工作人员");
        }
    }
    /**
     *按id查询文章
     * */
    @PostMapping("/{id}")
    public R<Article> selectByid(@PathVariable("id") Long id){
        try {
            Article article = articleservice.selectByid(id);
            return R.ok(article);
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            return R.fail("系统错误，联系工作人员");
        }
    }
    /**
     *分页查询文章
     * */
    @PostMapping("/page")
    public R<PageInfo<Article>> selectAll(@RequestBody ArticleQuery articleQuery){
        try {
            PageInfo<Article> page= articleservice.selectAll(articleQuery);
            return R.ok(page);
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return R.fail("系统错误，联系工作人员");
        }
    }
    /**
     *批量删除文章
     * */
    @PostMapping("/deleteall")
    public R<Void> delectall(@RequestBody List<Long> ids){
        try {
            articleservice.delectall(ids);
            return R.ok("删除成功");
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return R.fail("系统错误，联系工作人员");
        }
    }
    /**
     *按id删除文章
     * */
    @DeleteMapping("/{id}")
    public R<Void> delectByid(@PathVariable("id") Long id){
        try {
            articleservice.delectByid(id);
            return R.ok("删除成功");
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            return R.fail("系统错误，联系工作人员");
        }
    }
}
